package com.yk.common.web.interceptor;

import cn.hutool.core.collection.CollUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Enumeration;


/**
 * Feign请求拦截器（设置请求头，传递登录信息）
 *
 * @author lmx
 * @date 2023/10/18 16:52
 */
public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        if (RequestContextHolder.getRequestAttributes() == null) {
            return;
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                if (checkEssential(name)) {
                    requestTemplate.header(name, values);
                }
            }
        }
    }

    /**
     * 请求头必要传递参数过滤,只携带必要请求头信息
     *
     * @param name name
     * @return boolean
     */
    private boolean checkEssential(String name) {
        ArrayList<String> headers = CollUtil.newArrayList("satoken");
        return headers.stream().anyMatch(e -> e.equalsIgnoreCase(name));
    }
}